package day04;

import java.util.Scanner;

/**
 * @author yzh
 * @desc TODO
 * @date 2025/4/11
 */
public class BinarySearch {
    public static void main(String[] args) {

        int[] arr = { 15, 34, 43, 66, 87,99 };
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要查找的值: ");
        int target = sc.nextInt();

        int index = binarySearch(arr, target);

        if (index == -1) {
            System.out.println("未找到");
        }else {
            System.out.println("该值索引为"+index);
        }

    }

    public static int binarySearch(int[] arr, int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = (left + right) / 2;

            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }

        return -1; // 未找到
    }
}
